//
//  FBUtilities.m
//  HahnWinery
//
//  Created by HaiNguyenThanh on 4/19/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "FBUtilities.h"
#import "FBPoster.h"
#import "EndGameViewController.h"

@implementation FBUtilities
@synthesize fullName;
@synthesize loginDelegate;
@synthesize messageToPost;

- (id) init
{
	if (self = [super init])
	{
		NSLog(@"init facebook");
		fbSession = nil;
		
		fbSession = [FBSession
					 sessionForApplication:kFBAPIkey
					 secret:kFBSecretkey
					 delegate:self];
		[fbSession retain];
		[fbSession resume];
	}
    return self;
}

- (void)getFacebookName
{
	NSLog(@"Get facebook name");
	NSString* fql = [NSString stringWithFormat:@"select name from user where uid == %lld", fbSession.uid];
	NSDictionary* params = [NSDictionary dictionaryWithObject:fql forKey:@"query"];
	[[FBRequest requestWithDelegate:self] call:@"facebook.fql.query" params:params];
		
}

- (void) facebookLogin:(id)delegate
{
	FBLoginDialog* dialog = [FBLoginDialog alloc];
	[dialog initWithSession:[FBSession session]];
	if (delegate != nil)
	{
		dialog.delegate = self;
	}
	//else
	//{
		viewDelegate = delegate;
	//}	
	[dialog show];
	[dialog release];
}
- (void) postToWall:(NSString*)message
{
	[FBPoster PostToWall:message];
}
- (NSString*) getFullName
{
	return fullName;
}
#pragma mark -
#pragma mark FBSessionDelegate

/**
 * Called when a user has successfully logged in and begun a session.
 */
- (void)session:(FBSession*)session didLogin:(FBUID)uid
{
	NSLog(@"- (void)session:(FBSession*)session didLogin:(FBUID)uid");
	[self getFacebookName];
}

/**
 * Called when a user closes the login dialog without logging in.
 */
- (void)sessionDidNotLogin:(FBSession*)session
{
	NSLog(@"- (void)sessionDidNotLogin:(FBSession*)session");
}

/**
 * Called when a session is about to log out.
 */
- (void)session:(FBSession*)session willLogout:(FBUID)uid
{
	NSLog(@"- (void)session:(FBSession*)session willLogout:(FBUID)uid");
}

/**
 * Called when a session has logged out.
 */
- (void)sessionDidLogout:(FBSession*)session
{
	NSLog(@"- (void)sessionDidLogout:(FBSession*)session");
	[loginDelegate logout];
}
#pragma mark End FBSessionDelegate
#pragma mark -
#pragma mark FBRequestDelegate method

/**
 * Called just before the request is sent to the server.
 */
- (void)requestLoading:(FBRequest*)request
{
	NSLog(@"- (void)requestLoading:(FBRequest*)request");
}

/**
 * Called when the server responds and begins to send back data.
 */
- (void)request:(FBRequest*)request didReceiveResponse:(NSURLResponse*)response
{
	NSLog(@"- (void)request:(FBRequest*)request didReceiveResponse:(NSURLResponse*)response");
}

/**
 * Called when an error prevents the request from completing successfully.
 */
- (void)request:(FBRequest*)request didFailWithError:(NSError*)error
{
	NSLog(@"- (void)request:(FBRequest*)request didFailWithError:(NSError*)error");
}

/**
 * Called when a request returns and its response has been parsed into an object.
 *
 * The resulting object may be a dictionary, an array, a string, or a number, depending
 * on thee format of the API response.
 */
- (void)request:(FBRequest*)request didLoad:(id)result
{
	NSLog(@"- (void)request:(FBRequest*)request didLoad:(id)result");
	NSArray* users = result;
	NSLog(@"Result FB = %@", result);
	NSDictionary* user = [users objectAtIndex:0];
	fullName = [user objectForKey:@"name"];
	[fullName retain];
	//NSLog(@"name=%@", name);
	[loginDelegate getUserInfo];
}

/**
 * Called when the request was cancelled.
 */
- (void)requestWasCancelled:(FBRequest*)request
{
	NSLog(@"- (void)requestWasCancelled:(FBRequest*)request");
}
#pragma mark End

#pragma mark -
#pragma mark FBDialogDelegate Methods

/**
 * Called when the dialog succeeds and is about to be dismissed.
 */
- (void)dialogDidSucceed:(FBDialog*)dialog
{
	NSLog(@"- (void)dialogDidSucceed:(FBDialog*)dialog");
	NSLog(@"Do Posting Alert Message");
	/*if ([loginDelegate respondsToSelector:@selector(facebookFinishedLogin)]){
		[loginDelegate facebookFinishedLogin];
	}*/
	
	if([viewDelegate isKindOfClass:[EndGameViewController class]])
	{
		[viewDelegate createFBPostDialog];
	}
	else
	{
		[FBPoster PostToWall:@"Today, I have played the Politics Game. It's so fun!"];
	}

}

/**
 * Called when the dialog is cancelled and is about to be dismissed.
 */
- (void)dialogDidCancel:(FBDialog*)dialog
{
	NSLog(@"- (void)dialogDidCancel:(FBDialog*)dialog");
}

/**
 * Called when dialog failed to load due to an error.
 */
- (void)dialog:(FBDialog*)dialog didFailWithError:(NSError*)error
{
	NSLog(@"- (void)dialog:(FBDialog*)dialog didFailWithError:(NSError*)error");
	NSLog(@"Erro = %@", error);
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Message" 
													message:@"Can not connect to Facebook\n Check your network and try again"
												   delegate:nil 
										  cancelButtonTitle:@"Close"
										  otherButtonTitles:nil];
	[alert show];
	[alert release];
	[fbSession logout];
}

/**
 * Asks if a link touched by a user should be opened in an external browser.
 *
 * If a user touches a link, the default behavior is to open the link in the Safari browser, 
 * which will cause your app to quit.  You may want to prevent this from happening, open the link
 * in your own internal browser, or perhaps warn the user that they are about to leave your app.
 * If so, implement this method on your delegate and return NO.  If you warn the user, you
 * should hold onto the URL and once you have received their acknowledgement open the URL yourself
 * using [[UIApplication sharedApplication] openURL:].
 */
- (BOOL)dialog:(FBDialog*)dialog shouldOpenURLInExternalBrowser:(NSURL*)url
{
	return YES;
}
#pragma mark -
- (void)dealloc
{
	[super dealloc];
}
@end
